package com.it.day6;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * ClassName: ABADemo
 * Description: ABA问题
 *
 * @Author: csx
 * @Create: 2025/5/12 - 23:15
 * @version: v1.0
 */
public class ABADemo {
    static AtomicInteger atomicInteger = new AtomicInteger(100);
    //入参是初始值和版本号
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100,1);
    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();  //获取当前版本号
            System.out.println(Thread.currentThread().getName() + "\t默认版本号为：" + stamp);
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            boolean result = atomicStampedReference.compareAndSet(100, 101, stamp, stamp + 1);
            stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t当前是否成功：" + result + "\t1次修改版本号：" + stamp + "\t值为：" + atomicStampedReference.getReference());
            result = atomicStampedReference.compareAndSet(101, 100, stamp, stamp + 1);
            stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t当前是否成功：" + result + "\t2次修改版本号：" + stamp + "\t值为：" + atomicStampedReference.getReference());
        }, "t1").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();  //获取当前版本号
            System.out.println(Thread.currentThread().getName() + "\t默认版本号为：" + stamp);
            try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
            boolean result = atomicStampedReference.compareAndSet(100, 2025, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "\t当前是否成功：" + result + "\t版本号：" + stamp + "\t值为：" + atomicStampedReference.getReference());
        }, "t2").start();
    }

    /**
     * AtomicInteger 演示ABA问题
     */
    private static void abaProblem() {
        new Thread(() -> {
            atomicInteger.compareAndSet(100,101);
            atomicInteger.compareAndSet(101,100);
        }, "t1").start();

        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            atomicInteger.compareAndSet(100,10000);
            System.out.println(Thread.currentThread().getName() + "\t修改后：" + atomicInteger.get());
        }, "t2").start();
    }
}
















